package cn.com.dragonpass.psystem.common.redis;

import cn.com.dragonpass.common.redis.JedisBase;
import cn.com.dragonpass.common.redis.JedisBaseEnum;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * Jedis Cache 工具类
 */
@Slf4j
public class JedisUtils extends JedisBase {

    private static JedisUtils instance;

    /**
     * @return
     */
    public static JedisUtils getInstance() {
        if (instance == null) {
            synchronized (JedisUtils.class) {
                instance = new JedisUtils();
            }
        }
        return instance;
    }

    public JedisUtils() {
        super.setJedisEnum(JedisBaseEnum.DB0);
        super.setKeyPrefix("platform:system:");
    }

    public <T> T getObjectByClass(Class<T> resultClass, String... params) {
        String key = resultClass.getName() + "_";
        for (String p : params) {
            key += p + "_";
        }
        if (key.endsWith("_")) {
            key = key.substring(0, key.length() - 1);
        }
        return (T) super.getObject(key);
    }

    public void setObjectByClass(Object obj, int cacheSeconds, String... params) {
        String key = obj.getClass().getName() + "_";
        for (String p : params) {
            key += p + "_";
        }
        if (key.endsWith("_")) {
            key = key.substring(0, key.length() - 1);
        }
        super.setObject(key, obj, cacheSeconds);
    }

    public Map<String, String> getMapNotKeyPrefix(String key) {
        Map<String, String> value = null;
        Jedis jedis = null;

        try {
            jedis = this.getResource();
            if (jedis.exists( key)) {
                value = jedis.hgetAll(key);
            }
        } catch (Exception var8) {
            log.info(var8.getMessage(), var8);
        } finally {
            this.returnResource(jedis);
        }

        return value;
    }

}
